package com.micromall.admin;

import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.micromall.repository.EmployeeMapper;
import com.micromall.repository.OrderGoodsMapper;
import com.micromall.repository.OrderMapper;
import com.micromall.repository.entity.Order;
import com.micromall.repository.entity.admin.AdminListViewOrder;
import com.micromall.repository.entity.admin.AdminOrderDetail;
import com.micromall.repository.entity.common.OrderStatus;
import com.micromall.service.OrderService;
import com.micromall.service.ShortMessageService;
import com.micromall.service.TransactionalExecuteService;
import com.micromall.utils.*;
import com.micromall.utils.Condition.Criteria;
import com.micromall.web.resp.ResponseEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by zhangzx on 16/3/21.
 * 订单管理
 */
@RestController
@RequestMapping(value = "/admin/orders")
public class AdminOrdersController extends AdminBasicController {

	@Resource
	private OrderService                orderService;
	@Resource
	private OrderMapper                 orderMapper;
	@Resource
	private OrderGoodsMapper            orderGoodsMapper;
	@Resource
	private LogisticsUtils              logisticsUtils;
	@Resource
	private EmployeeMapper              employeeMapper;
	@Resource
	private ShortMessageService         shortMessageService;
	@Resource
	private TransactionalExecuteService transactionalExecuteService;

	@RequestMapping(value = "/list")
	public ResponseEntity<?> list(String query, Integer status, Boolean applyRefund, @RequestParam(defaultValue = "1") int pageNo, Integer
			pageSize) {
		Map<String, Object> params = Maps.newHashMap();
		params.put("orderBy", "id desc");
		params.put("query", StringUtils.trimToNull(query));
		if (applyRefund != null && applyRefund) {
			params.put("applyRefund", true);
		} else {
			params.put("status", status);
		}
		Page<AdminListViewOrder> orders = orderMapper.selectAdminPage(params, new RowBounds(pageNo, resizeLimit(pageSize)));
		for (AdminListViewOrder viewOrder : orders) {
			viewOrder.setGoodsList(
					orderGoodsMapper.selectMultiByWhereClause(Criteria.create().andEqualTo("order_no", viewOrder.getOrderNo()).build()));
		}
		return ResponseEntity.SuccessPage(orders);
	}

	@RequestMapping(value = "/details")
	public ResponseEntity<?> details(String orderNo) {
		AdminOrderDetail order = orderMapper.selectAdminDetail(orderNo);
		if (order == null) {
			throw new LogicException("订单不存在");
		}
		order.setGoodsList(orderGoodsMapper.selectMultiByWhereClause(Criteria.create().andEqualTo("order_no", orderNo).build()));
		return ResponseEntity.Success(order);
	}

	/**
	 * 订单物流信息
	 *
	 * @param orderNo 订单号
	 * @return
	 */
	@RequestMapping(value = "/logistics")
	public ResponseEntity<?> logistics(String orderNo) {
		Order order = orderMapper.selectOneByWhereClause(Criteria.create().andEqualTo("order_no", orderNo).build());
		if (order == null) {
			return ResponseEntity.Failure("订单不存");
		}

		if (order.getStatus() < OrderStatus.待收货) {
			return ResponseEntity.Failure("订单还未发货");
		}
		return ResponseEntity.Success(logisticsUtils.getLogisticsInfo(order));
	}

	/**
	 * @param orderNo
	 * @param agreed
	 * @param refuseReason
	 * @return
	 */
	@RequestMapping(value = "/refundAudit")
	public ResponseEntity<?> refundAudit(String orderNo, boolean agreed, String refuseReason) {
		orderService.refundAudit(orderNo, agreed, refuseReason);
		return ResponseEntity.Success();
	}

	@RequestMapping(value = "/delivery_company_list")
	public ResponseEntity<?> delivery_company_list() {
		Map<String, String> map = CommonEnvConstants.getLogistics();
		List<Map> list = Lists.newArrayList();
		list.addAll(map.keySet().stream().map(key -> new ChainMap<>("id", key).append("name", map.get(key))).collect(Collectors.toList()));
		return ResponseEntity.Success(list);
	}

	/**
	 * @param orderNo
	 * @param deliveryCode
	 * @param deliveryNumber
	 * @return
	 */
	@RequestMapping(value = "/delivery")
	public ResponseEntity<?> delivery(String orderNo, String deliveryCode, String deliveryNumber) {
		boolean success = orderService.delivery(orderNo, deliveryCode, deliveryNumber, false);
		if (success) {
			Order order = orderMapper.selectOneByWhereClause(Criteria.create().andEqualTo("order_no", orderNo).build());
			shortMessageService.sendDeliveryNotify(order.getConsigneePhone(), order.getConsigneeName(), orderNo);
		}
		return ResponseEntity.Success(success);
	}

	@RequestMapping(value = "/get_delivery")
	public ResponseEntity<?> get_delivery(String orderNo) {
		Order order = orderMapper.selectOneByWhereClause(Criteria.create().andEqualTo("order_no", orderNo).build());
		if (order == null) {
			throw new LogicException("订单不存在");
		}
		Map<String, Object> data = Maps.newHashMap();
		data.put("orderNo", orderNo);
		if (order.getStatus() >= OrderStatus.待收货) {
			data.put("deliveryCompany", order.getDeliveryCompany());
			data.put("deliveryCode", order.getDeliveryCode());
			data.put("deliveryNumber", order.getDeliveryNumber());
			data.put("deliveryTime", order.getDeliveryTime());
			if (CommonEnvConstants.ONESELF_LOGISTICS_CODE.equals(order.getDeliveryCode())) {
				data.put("employee", employeeMapper.selectByPrimaryKey(Integer.parseInt(order.getDeliveryNumber())));
			}
		}
		return ResponseEntity.Success(data);
	}

	@RequestMapping(value = "/update_delivery")
	public ResponseEntity<?> update_delivery(String orderNo, String deliveryCode, String deliveryNumber) {
		Order order = orderMapper.selectOneByWhereClause(Criteria.create().andEqualTo("order_no", orderNo).build());
		if (order == null) {
			throw new LogicException("订单不存在");
		}
		if (order.getStatus() != OrderStatus.待收货) {
			throw new LogicException("只有订单状态为待收货时才能修改物流信息");
		}
		return ResponseEntity.Success(orderService.delivery(orderNo, deliveryCode, deliveryNumber, true));
	}

	@RequestMapping(value = "/remark")
	public ResponseEntity<?> remark(String orderNo, String remark) {
		Order order = orderMapper.selectOneByWhereClause(Criteria.create().andEqualTo("order_no", orderNo).build());
		if (order == null) {
			throw new LogicException("订单不存在");
		}
		if (StringUtils.isEmpty(remark)) {
			throw new LogicException("备注内容不能为空");
		}
		Order _ModifyOrder = new Order();
		_ModifyOrder.setId(order.getId());
		_ModifyOrder.setRemark(remark);
		_ModifyOrder.setUpdateTime(new Date());
		transactionalExecuteService.execute(() -> orderMapper.updateByPrimaryKey(_ModifyOrder));
		return ResponseEntity.Success(true);
	}

	@RequestMapping(value = "/update_freight")
	public ResponseEntity<?> update_freight(String orderNo, float freight) {
		Order order = orderMapper.selectOneByWhereClause(Criteria.create().andEqualTo("order_no", orderNo).build());
		if (order == null) {
			throw new LogicException("订单不存在");
		}
		if (freight < 0) {
			throw new LogicException("运费不能小于0");
		}
		if (order.getStatus() != OrderStatus.待支付) {
			throw new LogicException("只有待支付订单才能修改运费");
		}
		Order _ModifyOrder = new Order();
		_ModifyOrder.setId(order.getId());
		_ModifyOrder.setFreight(Scale.scale(2, freight));
		_ModifyOrder.setTotalAmount(order.getTotalAmount().subtract(order.getFreight()).add(_ModifyOrder.getFreight()));
		_ModifyOrder.setUpdateTime(new Date());
		transactionalExecuteService.execute(() -> orderMapper.updateByPrimaryKey(_ModifyOrder));
		return ResponseEntity.Success(true);
	}

}
